<?php

namespace App\Http\Controllers\Business;

use App\Http\Controllers\Auth\Access;
use App\Http\Controllers\Controller;
use App\Models\Api\Files;
use App\Models\Business\Business;
use App\Models\Business\BusinessClassificationHe;
use App\Models\Business\BusinessClassificationThird;
use App\Models\Business\BusinessImage;
use App\Models\Business\BusinessTime;
use App\Models\Business\Food;
use App\Models\Business\FoodCategory;
use App\Models\User\Collection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Validator;
/**
 * @group 商家信息
 *
 * 采用 restful api
 *
 * Body Parameters 表示请求的所需要的参数
 *
 * Query Parameters 表示返回参数的名称
 */

class BusinessInfoController extends Controller
{
    /**
     * 商家信息查看
     *
     * @queryParam  name 联系人
     * @queryParam  user_title 商家名称
     * @queryParam  user_name 账户
     * @queryParam  password  密码
     * @queryParam  user_status 账户状态 0禁用 1启用
     * @queryParam  phone 手机号
     * @queryParam  address 地址
     * @queryParam  body 店铺介绍
     * @queryParam  consumption 人均消费
     * @queryParam  cost 配送费
     * @queryParam  time->start_time 营业开始时间
     * @queryParam  time->end_time 营业结束时间
     * @queryParam  time->day 营业时间 1：星期1 2：星期2 .. 0 星期天
     * @queryParam  sales 月销量
     * @queryParam  status 状态 0审核中1正常2失败
     * @queryParam  because 原因
     * @queryParam  shop_image 店铺形象图片
     * @queryParam  display_show 店铺展示图
     * @queryParam  Business_license 营业执照图
     * @queryParam  food  对应食品
     * @queryParam  food->classification->classification  对应分类
     * @queryParam  category-》name  对应类目
     * @queryParam  time_status 营业还是打烊 1 营业 0打烊
     *
     * @bodyParam search string  商家名称
     * @bodyParam phone string 联系人电话
     * @bodyParam name string 联系人姓名
     * @bodyParam class int 对应分类
     * @bodyParam user_name int 账号
     * @bodyParam  user_status int 账号状态 0禁用 1启用
     * @bodyParam status int 审核状态 0审核中 1成功 2失败
     */
    public function index(Request $request){
        $day=date("w");
        $time= time();

        $type=$request->user_type;
        if ($type==2){
            $id=$request->user_id;
            $data = $this->show($request,$id);
            return $data;
        }
        $query = Business::with('time')->with('shop_image')->with('classification')
            ->with('display_show')->with('Business_license')->where(function ($q) use($request){
            $request->has('status') && $q->where('status',$request->get('status'));
            $request->has('search') && $q->where('user_title','like',"%{$request->get('search')}%");
            $request->has('name') && $q->where('name','like',"%{$request->get('name')}%");
            $request->has('user_name') && $q->where('user_name','like',"%{$request->get('user_name')}%");
            $request->has('user_status') && $q->where('user_status',$request->get('user_status'));
            $request->has('phone') && $q->where('phone',$request->get('phone'));
            $request->user_type !=3 &&  $q->where('status',1);
        })->whereHas('classification',function ($q) use($request){
                $request->has('class') && $q->where('classification_id',$request->get('class'));
            });
        $query=pageQuery($query,$request)->toArray();

        foreach ($query['data'] as $k =>$v){
            if ($v['classification']!=null){
                $row=array();
                foreach ($v['classification'] as $key =>$value){

                    $rw=['id'=>$value['class']['0']['id'],'name'=>$value['class']['0']['name']];
                    array_push($row,$rw);
                }
               $query['data'][$k]['classification']=$row;
            }

            if($v['time']!=null){
                $row=array();
                foreach ($v['time'] as $key1 =>$value){

                    if($value['day'] == (int)$day){

                        if(strtotime($value['start_time']) <= $time && $time <= strtotime($value['end_time']))
                        {
                            $query['data'][$k]['time_status']=1;
                            break;
                        }else{
                            $query['data'][$k]['time_status']=0;
                        }
                    }else{
                        $query['data'][$k]['time_status']=0;
                    }
                }
            }else{
                $query['data'][$k]['time_status']=0;
            }
            if ($type !=3){
                unset($query['data'][$k]['password']);
            }
            }
        return response()->json($query,200);

    }
    /**
     * 商家信息查看单条
     *
     * @queryParam  name 联系人
     * @queryParam  user_title 商家名称
     * @queryParam  user_name 账户
     * @queryParam  password  密码
     * @queryParam  user_status 账户状态 0禁用 1启用
     * @queryParam  phone 手机号
     * @queryParam  address 地址
     * @queryParam  body 店铺介绍
     * @queryParam  cost 配送费
     * @queryParam  consumption 人均消费
     * @queryParam  time->start_time 营业开始时间
     * @queryParam  time->end_time 营业结束时间
     * @queryParam  time->day 营业时间 1：星期1 2：星期2 .. 0 星期天
     * @queryParam  sales 月销量
     * @queryParam  status 状态 0审核中1正常2失败
     * @queryParam  because 原因
     * @queryParam  shop_image 店铺形象图片
     * @queryParam  display_show 店铺展示图
     * @queryParam  Business_license 营业执照图
     * @queryParam  food->classification->classification  对应分类
     * @queryParam  category->name  对应类目
     * @queryParam  classification->class  对应商家分类
     * @queryParam  category->food  对应类目的商品
     * @queryParam  time_status 营业还是打烊 1 营业 0打烊
     *
     */
    public function show(Request $request,$pk){
        $day=date("w");
        $time= time();
        $rew = Business::where(['user_status'=>1])->with('time')->with('classification')->with('food')->with('shop_image')
            ->with('Business_license')->with('display_show')->find($pk);
        $food=$rew['food'];
        if ($food !=null){
            $row=array();
            foreach ($food as $k => $v){
                if ($v['category']!=null){
                    array_push($row,$v['category']['id']);
                }
            }
            $row=array_unique($row);
            $reow=array();
            foreach ($row as $key =>$value){
                $data = FoodCategory::whereHas('foods',function (Builder $q) use ($pk)
                {
                     $q->where('business_id','=',$pk);
                })->where('id',$value)->get()->toArray();
                $ids = [];
                array_walk($data,function ($value,$key) use (&$ids)
                {
                    $ids [] = $value['id'];
                });
                if($data != [])
                {
                    $foods = Food::whereIn('category_id',$ids)->where('status',1)->with('image');
                        $foods->where('business_id','=',$pk);
                    $foods = $foods->get()->toArray();
                    foreach($data as $k => $v){
                        $data[$k]['foods'] = [];
                        foreach ($foods as $key=>$val){
                            if($val['category_id'] == $v['id'])
                                array_push($data[$k]['foods'],$foods[$key]);
                        }
                    }
                }
                array_push($reow,$data);
            }
            unset($rew['food']);
                unset($rew['password']);

            $rew['category']=$reow;

            if($rew['time']!=null){
                $row=array();
                foreach ($rew['time'] as $key1 =>$value){
                    if($value['day'] == $day){
                        $i=strtotime($value['start_time']);
                        if(strtotime($value['start_time']) <= $time && $time <= strtotime($value['end_time']))
                        {
                            $rew['time_status']=1;
                        }else{
                            $rew['time_status']=0;
                        }
                    }
                }
            }
            if ($request->user_type==1){
                $coll=Collection::where(['user_id'=>$request->user_id,'business_id'=>$pk])->first();
                if ($coll!=null){
                    $rew['collection']=1;
                }else{
                    $rew['collection']=0;
                }
            }
        }
        if($rew == []){
            return response()->json(["message"=>"没有该信息"],404);
        }else{
            return response()->json($rew,200);
        }
    }

    /**
     * 商家号是否重复
     *
     * @bodyParam  user_name string 账号
     */
    public function search(Request $request){
        if (!$request->has('user_name')){
            return response()->json(["message"=>"没有传user_name"],441);
        }
        $row=Business::where('user_name',$request->get('user_name'))->first();
        if ($row !=null){
            return response()->json(["message"=>"有对应商家账号"],451);
        }else{
            return response()->json(["message"=>"可以使用"],200);
        }
    }
    /**
     * 商家信息添加
     *
     * @bodyParam  name string 联系人
     * @bodyParam  user_title string  商家名称
     * @bodyParam   user_name string 账户
     * @bodyParam  password string required  密码
     * @bodyParam  user_status 账户状态
     * @bodyParam  phone string required 手机号
     * @bodyParam  address string 地址
     * @bodyParam  body string  店铺介绍
     * @bodyParam  consumption int optional 人均消费
     * @bodyParam  shop_image int 店铺形象图片
     * @bodyParam  display_show int  店铺展示图
     * @bodyParam  Business_license int 营业执照图
     * @bodyParam  time {"start_time": "9:53:19","end_time": "18:33:01","day": [1,2,3]}
     * @bodyParam  classification json required 商家分类id  {"0":2,"1":6}
     * classification {"0":{"id":3}} 删除对应商家分类  {{"1":6}}  添加对应商家分类
     *
     * 503 添加商家失败
     * 504 添加失败
     * 505 添加分类失败
     * 506 添加失败
     */
    public function store(Request $request)
    {
        try{
            $e = genValidate();
            $validator = Validator::make($request->all(),$e);
            if($validator->fails()){
                return response()->json($validator->errors()->messages(),400);
            }
            $data=$request->all();
            if ($request->get('time')!=null){
                unset($data['time']);
            }
            if ($request->get('classification')!=null){
                unset($data['classification']);
            }
//            if ($data['password']!=null){
//                $pas=md5($data['password']);
//                $data['password']=$pas;
//            }
            DB::beginTransaction();
            if ($request->get('user_name')!=null){
                $row=Business::where('user_name',$request->get('user_name'))->first();
                if ($row !=null){
                    return response()->json(["message"=>"有对应商家账号"],451);
                }
            }
           if ($request->get('display_show')){
                $image=json_decode($request->get('display_show'),true);

                unset($data['display_show']);
                $id=Business::insertGetId($data);
                if (!$id){
                    return response()->json(["message"=>"添加商家失败"],503);
                }
                foreach ($image as $k=>$v){
                    $value=array(
                        'business_id'=>$id,
                        'image_id'=>$v
                    );

                    $img=BusinessImage::create($value);
                    if (!$img){
                        DB::rollBack();
                        return response()->json(["message"=>"添加中间表失败"],501);
                    }
                }
            }else{
               $id=Business::insertGetId($data);
               if (!$id){
               DB::rollBack();
                   return response()->json(["message"=>"添加2失败"],505);
               }
           }

            if ($request->get('time')!=null){
                $time=json_decode($request->get('time'),true);
                foreach ($time['day'] as $k=>$v){

                    $v=array_merge_recursive(array('day'=>$v),array('business_id'=>$id,'start_time'=>$time['start_time'],'end_time'=>$time['end_time']));
                    $bt=BusinessTime::create($v);
                    if (!$bt){
                        DB::rollBack();
                        return response()->json(["message"=>"添加时间失败"],504);
                    }
                }
            }
            if ($request->get('classification')!=null){
                $class=json_decode($request->get('classification'),true);
                foreach($class as $k=>$v){
                    $classification_v=array(
                        'business_id'=>$id,
                        'classification_id'=>$v
                    );
                   $cla_bus=BusinessClassificationHe::insertGetId($classification_v);
                   if (!$cla_bus){
                       DB::rollBack();
                       return response()->json(["message"=>"添加分类失败"],505);
                   }
                }
            }
            DB::commit();
            return response()->json(["message"=>"添加成功"],201);
        }catch (QueryException $e){
            DB::rollBack();
            return response()->json(["message"=>"添加失败"],506);
        }
    }
    /**
     * 商家信息修改
     *
     * @bodyParam  name string 联系人
     * @bodyParam  user_title string 商家名称
     * @bodyParam   user_name string 账户
     * @bodyParam  password string   密码
     * @bodyParam  user_status int 账户状态 0禁用 1启用
     * @bodyParam  phone string 手机号
     * @bodyParam  address string 地址
     * @bodyParam  body string 店铺介绍
     * @bodyParam  status int 店铺状态 0审核中 1正常 2失败
     * @bodyParam  consumption int 人均消费
     * @bodyParam  cost float 配送费
     * @bodyParam  because string 原因
     * @bodyParam  shop_image string 店铺形象图片
     * @bodyParam  display_show string 店铺展示图  {"0":{"id":8}} 删除图片 {"1":3} 添加图片
     * @bodyParam  Business_license string 营业执照图
     * @bodyParam  classification int 商家分类id
     *
     * classification {"0":{"id":3}} 删除对应商家分类  {{"1":6}}  添加对应商家分类
     *
     * 501  商家没有权限修改原因
     * 502  只有商家才能改配送费
     * 503  商家没有权限修改状态值
     * 504  删除图片失败
     * 505  添加中间表失败
     * 506  修改时间失败
     * 507  删除时间失败
     * 508  添加时间失败
     * 509  删除分类中间表失败
     * 510  添加分类中间表失败
     * 511  修改失败
     * 512  修改失败
     */
    public function update(Request $request,$pk){
        $type=$request->user_type;
       if ($request->has('status')){
            if ($type==2)
                return response()->json(["message"=>"商家没有权限修改状态值"],503);
        }
        if ($request->has('because')){
            if ($type==2)
                return response()->json(["message"=>"商家没有权限修改原因"],501);
        }
       if ($request->has('cost')){
           if ($type!=2)
               return response()->json(["message"=>"只有商家才能改配送费"],502);
       }

        $e = genValidate();
        $validator = Validator::make($request->all(),$e);
        if($validator->fails()){
            return response()->json($validator->errors()->messages(),400);
        }
        if ($request->user_type == 2){
            $pk = $request->user_id;
        }
        $carkind = Business::find($pk)->toArray();
        if($carkind == []){
            return response()->json(["message"=>"没有该信息"],404);
        }
        $data=$request->all();
        try {
            DB::beginTransaction();
           if ($request->get('display_show')){
                unset($data['display_show']);
                $image=json_decode($request->get('display_show'),true);
                foreach($image as $k=>$v) {
                    if ($v['id']!=null){
                        $business_delete=BusinessImage::where('image_id',$v['id'])->delete();
                        $image_delete=Files::where('id',$v['id'])->delete();
                        if ( $business_delete == false ||$image_delete == false){
                            DB::rollBack();
                            return response()->json(["message"=>"删除图片失败"],504);
                        }
                    }else{
                        $value=array(
                            'business_id'=>$pk,
                            'image_id'=>$v
                        );
                        $img=BusinessImage::insertGetId($value);
                        if (!$img){
                            DB::rollBack();
                            return response()->json(["message"=>"添加中间表失败"],505);
                        }
                    }
                }
                };
           if ($request->get('classification')){
               unset($data['classification']);
               $class=json_decode($request->get('classification'),true);
               foreach ($class as $k=>$v){
                   if ($v['id']!=null){
                       $class_v=array(
                           'business_id'=>$pk,
                           'classification_id'=>$v['id']
                       );
                        $delete=BusinessClassificationHe::where($class_v)->delete();
                        if (!$delete){
                            DB::rollBack();
                            return response()->json(["message"=>"删除分类中间表失败"],509);
                        }
                   }else{
                       $class_v=array(
                           'business_id'=>$pk,
                           'classification_id'=>$v
                       );
                        $insert=BusinessClassificationHe::insertGetId($class_v);
                       if (!$insert){
                           DB::rollBack();
                           return response()->json(["message"=>"添加分类中间表失败"],510);
                       }
                   }
               }
           };
            DB::commit();
            if ($data!=null){
                $info=Business::where('id',$pk)->update($data);
                if (!$info){
                    return response()->json(["message"=>"修改失败"],511);
                }
            }
                return response()->json(["message"=>"修改成功"],200);
        }catch (QueryException $e){
            DB::rollBack();
            return response()->json(["message"=>"修改失败"],512);
        }
    }
    /**
     * 商家删除(单条)
     *
     */
    public function destroy($pk){

        $data = Business::find($pk);
        if($data == []){
            return response()->json(["message"=>"没有该信息"],404);
        }
        $data->delete();
        return response()->json(["message"=>"删除成功"],200);
    }
    /**
     * 商家删除（多个才传）
     *
     * @bodyParam  business json  商家id {"0":{"id":23},"1":{"id":24}}
     *
     */
    public function alldelete(Request $request){
        $business=json_decode($request->get('business'),true);
        DB::beginTransaction();
        foreach ($business as $k=>$v){
        $data=Business::find($v['id']);
            if($data == []){
                DB::rollBack();
                return response()->json(["message"=>"没有该信息"],404);
            }
            $data->delete();
        }
        DB::commit();
        return response()->json(["message"=>"删除成功"],200);
    }

}
